import JsonP from 'jsonp'
import axios from 'axios'
import { Modal } from 'antd'
import Utils from '../utils/utils'

// 导出个对象给页面使用
export default class Axios {
    
    static requestList(_this, url, params, isMock) {
        let data = {
            params,
            isMock
        }
        this.ajax({
            url,
            data
        }).then((data) => {
            if(data && data.result) {
                let list = data.result.item_list.map((item, index) => {
                    item.key = index
                    return item
                })
                _this.setState({
                    list,
                    pagination: Utils.pagination(data, (current) => {
                        _this.params.page = current
                        _this.requestList()
                    })
                })
            }
        })
    }

    // 定义一个静态方法, options大对象
    static jsonp(options){
        return new Promise((resolve, reject) => {
            JsonP(options.url, {
                param: 'callback'
            },function(err, response) {
                if(response.status === 'success') {
                    resolve(response)
                }else {
                    reject(response.message);
                }
            })
        })
    }
    //封装一个ajax方法
    static ajax(options) {
        // 没数据之前出现loading效果
        let loading
        if(options.data && options.data.isShowLoading !== false) {
            loading = document.getElementById('ajaxLoading')
            loading.style.display = 'block'
        }
        let baseApi = ''
        console.log('options', options.data)
        if(options.data.isMock){
            baseApi = 'https://easy-mock.com/mock/5bfa7a76ca4e39455ecc67b7/mockapi'
        }else {
            baseApi = 'https://easy-mock.com/mock/5bfa7a76ca4e39455ecc67b7/mockapi'
        }
        return new Promise((resolve, reject) => {
            axios({
                url: options.url,
                method: 'get',
                baseURL: baseApi,
                timeout: 5000,
                params: (options.data && options.data.params) || ''
            }).then(response => {
                //  有了数据之后 把loading效果关闭
                if(options.data && options.data.isShowLoading !== false) {
                    loading = document.getElementById('ajaxLoading')
                    loading.style.display = 'none'
                }
                if(response.status == '200') {  //http请求的状态码， 200表示请求成功
                    let res = response.data
                    if(res.code == '0'){  // res.code表示业务层面的请求数据成功
                        resolve(res)
                    }else{
                        Modal.info({
                            title: '提示',
                            content: res.data.msg
                        })
                    }
                } else {
                    reject(response.data)
                }
            })
        })
    }

}